package com.atguigu.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by 小可乐$ on 2024/9/10$ 20:10$
 * description: 生产者消息确认机制：生产者有没有生产成功传递给交换机，交换机到队列
 * 消息从 producer 到 exchange 则会返回一个 confirmCallback 。
 * 消息从 exchange–>queue 投递失败则会返回一个 returnCallback 。
 */
@Component
@Slf4j//日志
public class MQProducerAckConfig implements RabbitTemplate.ConfirmCallback,
        RabbitTemplate.ReturnsCallback {
//    重写两个方法
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @PostConstruct//定义初始化，启动方法,this为当前类对象
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }
    /**
     *
     * ack：签收回执，true，签收成功
     *
    * */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送到交换机成功！数据：" + correlationData);
        } else {
            log.info("消息发送到交换机失败！数据：" + correlationData + " 原因：" + cause);
        }
    }

    /**
     * 失败执行
     * */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("消息主体: " + new String(returned.getMessage().getBody()));
        log.info("应答码: " + returned.getReplyCode());
        log.info("描述：" + returned.getReplyText());
        log.info("消息使用的交换器 exchange : " + returned.getExchange());
        log.info("消息使用的路由键 routing : " + returned.getRoutingKey());
    }
}
